package com.bytedance.common.plugin.framework.update;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.text.TextUtils;

import com.bytedance.common.plugin.framework.PluginManager;
import com.bytedance.common.plugin.framework.model.DeletePluginItem;
import com.bytedance.common.plugin.framework.model.InstallPluginItem;
import com.bytedance.common.plugin.framework.model.Plugin;
import com.bytedance.common.plugin.framework.model.ProcessType;
import com.bytedance.common.utility.Logger;
import com.bytedance.common.utility.c.SharedPreferenceCompat;
import com.bytedance.common.utility.collection.WeakHandler;
import com.bytedance.common.utility.collection.WeakHandler.Callback;
import com.ss.android.common.AppContext;
import com.ss.android.newmedia.h.DexInstallThread;
import com.ss.android.newmedia.h.PluginInstaller;
import com.ss.android.newmedia.h.pluginInstallThread;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;

public class PluginUpdateHelper implements PluginDownloadListener, Callback {
    static String downloadDir = null;
    private static String pluginDir = null;
    private static Map<String, InstallPluginItem> sUpdatePluginItemMap = new ConcurrentHashMap();
    private static Map<String, DeletePluginItem> sDeletePluginItemMap = new ConcurrentHashMap();
    private static PluginUpdateHelper sInstance = null;

    protected final WeakHandler mWeakHandler = new WeakHandler(Looper.getMainLooper(), this);
    private Context mContext;
    private ProcessType mProcessType;
    private AtomicBoolean e;
    private String ssPluginConfigUrl = null;
    private boolean j;
    private int updateVersionCode;
    private int manifestVersionCode;
    private UpdatePluginExtras mUpdatePluginExtras;
    private ConnectivityReceiver mConnectivityReceiver;

    private PluginUpdateHelper(Context context, int updateVersionCode, int arg8, ProcessType processType, UpdatePluginExtras arg10) {
        this.j = false;
        this.mConnectivityReceiver = new ConnectivityReceiver();
        this.e = new AtomicBoolean(false);
        this.mContext = context.getApplicationContext();
        this.updateVersionCode = updateVersionCode;
        this.manifestVersionCode = arg8;
        this.mProcessType = processType;
        pluginDir = this.mContext.getFilesDir() + "/ss_plugins";
        try {
            PluginUpdateHelper.downloadDir = Environment.getExternalStorageDirectory().getPath() + "/Android/data/" + this.mContext.getPackageName() + "/files/plugins";
            File downloadDir = new File(PluginUpdateHelper.downloadDir);
            if (!downloadDir.exists()) {
                downloadDir.mkdirs();
            }
        } catch (Throwable throwable) {
            try {
                PluginUpdateHelper.downloadDir = this.mContext.getFilesDir() + "/ss_plugins";
            } catch (Exception e) {
                PluginUpdateHelper.downloadDir = null;
            }
        }

        this.mUpdatePluginExtras = arg10;
        if (this.mUpdatePluginExtras != null) {
            com.ss.android.newmedia.h.a.c();
        }

        if (this.mProcessType == ProcessType.MAIN) {

        } else {

            try {
                KillApplicationReceiver killApplicationReceiver = new KillApplicationReceiver();
                IntentFilter intentFilter = new IntentFilter();
                intentFilter.addAction("com.bytedance.common.plugin.framework.update.killApplication");
                this.mContext.registerReceiver(killApplicationReceiver, intentFilter);
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        }

        try {
            if (this.mProcessType == ProcessType.MAIN) {

            } else {
                if (!this.j) {
                    this.loadData();
                    this.j = true;
                }

                if (this.mProcessType.getTypeValue() >= ProcessType.MAIN.getTypeValue()) {

                } else {
                    this.handleTryInstall(false);
                }
            }
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }

        if (this.mProcessType != ProcessType.MAIN) {
            this.mContext.registerReceiver(this.mConnectivityReceiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
            return;
        }

        if (this.e.get()) {
            this.mContext.registerReceiver(this.mConnectivityReceiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
            return;
        }

        synchronized (this) {
            try {
                if (this.j) {

                } else {
                    this.loadData();
                    if (this.mProcessType != ProcessType.MAIN) {
                        this.j = true;
                    } else {
                        SharedPreferences v0_4 = this.getLitePluginInfoSp();
                        if (this.ssPluginConfigUrl != null && (this.ssPluginConfigUrl.equals(com.bytedance.common.plugin.a.getPluginDepend().ssPluginConfigUrl()))) {
                            this.j = true;
                        } else {
                            PluginUpdateHelper.sUpdatePluginItemMap.clear();
                            PluginUpdateHelper.sDeletePluginItemMap.clear();
                            SharedPreferences.Editor editor = v0_4.edit();
                            editor.clear();
                            SharedPreferenceCompat.commit(editor);
                            Intent intent = new Intent();
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            intent.setAction("com.bytedance.common.plugin.framework.update.killApplication");
                            this.mContext.sendBroadcast(intent);
                        }
                    }
                }
            } catch (Throwable v0) {

            }
        }
        if (Logger.debug()) {
            Logger.d("PluginUpdateHelper", "startInstallAndCheckUpdate");
        }

        this.handleTryInstall(false);
        this.e.getAndSet(true);
        com.bytedance.common.utility.b.a.a(new AsyncTask() {
            private Void a() {
                try {
                    PluginUpdateHelper.this.doUpdate();
                } catch (Exception v0) {
                    v0.printStackTrace();
                }
                PluginUpdateHelper.this.e.getAndSet(false);
                return null;
            }

            protected final Object doInBackground(Object[] arg2) {
                return this.a();
            }
        }, new Void[0]);
        this.mContext.registerReceiver(this.mConnectivityReceiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
    }

    public static InstallPluginItem a(String arg2) {
        if (PluginUpdateHelper.sUpdatePluginItemMap != null) {
            try {
                return PluginUpdateHelper.sUpdatePluginItemMap.get(arg2);
            } catch (Throwable throwable) {
                throwable.printStackTrace();
                return null;
            }
        }

        return null;
    }

    public static PluginUpdateHelper create(Context context, int updateVersionCode, int manifestVersion, ProcessType processType, UpdatePluginExtras arg11) {
        if (PluginUpdateHelper.sInstance == null) {
            synchronized (PluginUpdateHelper.class) {
                if (PluginUpdateHelper.sInstance == null) {
                    PluginUpdateHelper.sInstance = new PluginUpdateHelper(context, updateVersionCode, manifestVersion, processType, arg11);
                }
            }
        }

        return PluginUpdateHelper.sInstance;
    }

    public static PluginUpdateHelper getInstance() {
        if (PluginUpdateHelper.sInstance == null) {
            throw new IllegalStateException("PluginUpdateHelper not init");
        }

        return PluginUpdateHelper.sInstance;
    }

    public static List<InstallPluginItem> getUpdatePluginItemList() {
        List<InstallPluginItem> pluginItemList = null;
        if (PluginUpdateHelper.sUpdatePluginItemMap == null) {
            return null;
        }

        try {
            Iterator<Map.Entry<String, InstallPluginItem>> iterator = PluginUpdateHelper.sUpdatePluginItemMap.entrySet().iterator();
            while (iterator.hasNext()) {
                InstallPluginItem pluginItem = iterator.next().getValue();
                if (pluginItem != null && (pluginItem.isReady())) {
                    if (pluginItemList == null) {
                        pluginItemList = new ArrayList();
                    }
                    pluginItemList.add(pluginItem);
                }
            }
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return pluginItemList;
    }

    public static List getDeletePluginItemList() {
        if (PluginUpdateHelper.sDeletePluginItemMap == null) {
            return null;
        }

        ArrayList<DeletePluginItem> deletePluginItemArrayList = null;
        try {
            Iterator<Map.Entry<String, DeletePluginItem>> iterator = PluginUpdateHelper.sDeletePluginItemMap.entrySet().iterator();
            while (true) {
                if (!iterator.hasNext()) {
                    return deletePluginItemArrayList;
                }
                DeletePluginItem deletePluginItem = iterator.next().getValue();
                if (deletePluginItem != null) {
                    if (deletePluginItemArrayList == null) {
                        deletePluginItemArrayList = new ArrayList();
                    }
                    deletePluginItemArrayList.add(deletePluginItem);
                }
                break;
            }
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return deletePluginItemArrayList;
    }

    private static void deleteAllPlugins() {
        if (PluginUpdateHelper.sUpdatePluginItemMap != null
                && !PluginUpdateHelper.sUpdatePluginItemMap.isEmpty()
                && !android.support.design.a.isTextEmpty(PluginUpdateHelper.downloadDir)) {
            try {
                File downloadDirFile = new File(PluginUpdateHelper.downloadDir);
                if (!downloadDirFile.exists()) {
                    return;
                }

                File[] pluginFiles = downloadDirFile.listFiles();
                LinkedHashSet set = new LinkedHashSet();
                int v3 = pluginFiles.length;
                for (int i = 0; i < v3; ++i) {
                    File pluginFile = pluginFiles[i];
                    if (!pluginFile.isDirectory()) {
                        String path = pluginFile.getAbsolutePath();
                        if (path.endsWith(".pl")) {
                            set.add(path);
                        }
                    }
                }

                Iterator<Map.Entry<String, InstallPluginItem>> iterator = PluginUpdateHelper.sUpdatePluginItemMap.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry<String, InstallPluginItem> entry = iterator.next();
                    if (entry == null) {
                        continue;
                    }
                    set.remove(entry.getValue().getDstFilePath(PluginUpdateHelper.downloadDir));
                }

                Iterator<String> stringIterator = set.iterator();
                while (stringIterator.hasNext()) {
                    new File(stringIterator.next()).delete();
                }
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        }
    }

    public final void handleTryInstall(boolean force) {
        if (Logger.debug()) {
            Logger.d("PluginUpdateHelper", "handleTryInstall");
        }

        com.bytedance.common.plugin.a.updatePluginItems();
        if (this.mUpdatePluginExtras != null) {
            try {
                PluginInstaller.setOnPluginInstallFinishListener(mUpdatePluginExtras.mOnPluginInstallFinishListener);
                PluginInstaller.tryInstall(mUpdatePluginExtras.mAppContext, force, new boolean[]{true});
            } catch (Throwable throwable) {
                Logger.e("Plugin", "Try install plugin failed.", throwable);
            }
            com.ss.android.l.c.c();
        }
    }

    private void a(InstallPluginItem installPluginItem) {
        if (installPluginItem != null) {
            try {
                installPluginItem.saveData(this.getLitePluginInfoSp().edit(), true);
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        }
    }

    public final void onDownloadProgressChanged() {
    }

    public final void onReceiveHeaderInfo(String packageName, int contentLength, String etag) {
        if (this.mProcessType == ProcessType.MAIN) {
            Message message = this.mWeakHandler.obtainMessage(3);
            Object[] objs = new Object[3];
            objs[0] = packageName;
            objs[1] = Integer.valueOf(contentLength);
            objs[2] = etag;
            message.obj = objs;
            this.mWeakHandler.sendMessage(message);
        }
    }

    public final void onDownloadStatusChanged(String packageName, DownloadStatus downloadStatus) {
        if (this.mProcessType == ProcessType.MAIN) {
            Message message = this.mWeakHandler.obtainMessage(4);
            message.obj = new Object[]{packageName, downloadStatus};
            this.mWeakHandler.sendMessage(message);
        }
    }

    final void doUpdate() {
        if (this.mProcessType == ProcessType.MAIN) {
            if (Logger.debug()) {
                Logger.d("PluginUpdateHelper", "doUpdate");
            }

            if (this.checkUpdate()) {
                this.mWeakHandler.sendEmptyMessage(0);
                return;
            }

            this.mWeakHandler.sendEmptyMessage(1);
        }
    }

    private void handlePluginDownload() {
        int v1 = 0;
        Object v0_1;
        if (this.mProcessType == ProcessType.MAIN) {
            if (Logger.debug()) {
                Logger.d("PluginUpdateHelper", "handlePluginDownload");
            }

            if (!com.bytedance.common.plugin.a.getPluginDepend().allowNetwork(this.mContext)) {
                return;
            }

            if (PluginUpdateHelper.sUpdatePluginItemMap == null) {
                return;
            }

            Iterator v3 = PluginUpdateHelper.sUpdatePluginItemMap.entrySet().iterator();
            while (true) {
                label_19:
                if (!v3.hasNext()) {
                    return;
                }

                v0_1 = ((Map.Entry) v3.next()).getValue();
                if (v0_1 == null) {
                    continue;
                }


                if (((InstallPluginItem) v0_1).isReady() || ((InstallPluginItem) v0_1).mAsyncTask != null && ((InstallPluginItem) v0_1).mAsyncTask.getStatus() != AsyncTask.Status.FINISHED) {
                    v1 = 0;
                } else {
                    v1 = 1;
                }

                if (v1 == 0) {
                    continue;
                }

                Logger.d("PluginUpdateHelper", "startDownload = " + ((InstallPluginItem) v0_1).packageName);
                if (this.mProcessType != ProcessType.MAIN) {
                    continue;
                }

                if (v0_1 == null) {
                    continue;
                }

                ((InstallPluginItem) v0_1).mAsyncTask = new DownloadPluginTask(((InstallPluginItem) v0_1));
                com.bytedance.common.utility.b.a.a(((InstallPluginItem) v0_1).mAsyncTask, new Object[0]);
                continue;
            }
        }
    }

    private boolean checkUpdate() {
        if (this.mProcessType != ProcessType.MAIN) {
            return false;
        }

        if (Logger.debug()) {
            Logger.d("PluginUpdateHelper", "checkUpdate");
        }

        String ssPluginConfigUrl = com.bytedance.common.plugin.a.getPluginDepend().ssPluginConfigUrl();
        if (TextUtils.isEmpty(ssPluginConfigUrl)) {
            return false;
        }

        this.ssPluginConfigUrl = ssPluginConfigUrl;
        LinkedHashMap<String, String> map = new LinkedHashMap();
        if (this.updateVersionCode > 0) {
            map.put("update_version_code", String.valueOf(this.updateVersionCode));
        }

        if (this.manifestVersionCode > 0) {
            map.put("manifest_version_code", String.valueOf(this.manifestVersionCode));
        }

        List<Plugin> pluginList = PluginManager.getPlugins();
        JSONArray ja = new JSONArray();
        Iterator<Plugin> iterator = pluginList.iterator();
        try {
            while (true) {
                if (!iterator.hasNext()) {
                    break;
                }

                Plugin plugin = iterator.next();
                JSONObject jsonObject = null;
                if (plugin != null) {
                    jsonObject = new JSONObject();
                    jsonObject.put("package_name", plugin.packageName);
                    jsonObject.put("apk_version_code", plugin.mPackageInfo.versionCode);
                }
                if (jsonObject != null) {
                    ja.put(jsonObject);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            if (ja.length() > 0) {
                map.put("plugin_items", ja.toString());
            }

            map.put("time", String.valueOf(System.currentTimeMillis()));
            String url = com.bytedance.common.plugin.a.getPluginDepend().getPluginDownloadUrl(ssPluginConfigUrl, map);
            File pluginDir = new File(PluginUpdateHelper.pluginDir);
            if (!pluginDir.exists()) {
                pluginDir.mkdirs();
            }

            if (!pluginDir.isDirectory()) {
                Logger.w("PluginUpdateHelper", "ss_plugin_json dir not exists");
            }

            File pluginJsonFile = new File(PluginUpdateHelper.pluginDir, "ss_plugin.json");
            if (pluginJsonFile.exists()) {
                pluginJsonFile.delete();
            }

            String pluginJsonContent = com.bytedance.common.plugin.a.getPluginDepend().downloadFile(url, PluginUpdateHelper.pluginDir, "ss_plugin.json")
                    ? com.bytedance.common.plugin.a.getPluginDepend().getFileContent(pluginJsonFile) : "";
            if (TextUtils.isEmpty(pluginJsonContent)) {
                return false;
            }

            JSONObject jo = new JSONObject(pluginJsonContent);
            if (!"success".equals(jo.getString("message"))) {
                return false;
            }

            JSONObject dataJO = jo.getJSONObject("data");
            JSONArray updatePluginsJA = dataJO.optJSONArray("update_plugins");
            JSONArray deletePlugins = dataJO.optJSONArray("delete_plugins");
            ConcurrentHashMap<String, InstallPluginItem> installItemMap = new ConcurrentHashMap();
            if (updatePluginsJA != null) {
                int i = 0;
                while (i < updatePluginsJA.length()) {
                    dataJO = updatePluginsJA.getJSONObject(i);
                    int targetVersion = dataJO.optInt("target_version");
                    InstallPluginItem installPluginItem = InstallPluginItem.fromJO(dataJO);
                    if (this.updateVersionCode <= 0 || this.updateVersionCode >= targetVersion) {
                        if (installPluginItem != null && (installPluginItem.b())) {
                            if (Logger.debug()) {
                                Logger.d("PluginUpdateHelper", "pluginItem = " + installPluginItem.packageName);
                            }

                            InstallPluginItem installPluginItem1 = PluginUpdateHelper.sUpdatePluginItemMap.get(installPluginItem.packageName);
                            if (installPluginItem1 == null) {
                                installPluginItem1 = com.bytedance.common.plugin.a.getInstallPluginItem(installPluginItem.packageName);
                            }

                            if (!installPluginItem.a(installPluginItem1)) {
                                if (installPluginItem1 != null) {
                                    installItemMap.put(installPluginItem1.packageName, installPluginItem1);
                                }
                                ++i;
                                continue;
                            }

                            if (Logger.debug()) {
                                Logger.d("PluginUpdateHelper", "pluginItem shouldStay");
                            }
                            installItemMap.put(installPluginItem.packageName, installPluginItem);
                        }
                    } else if (installPluginItem != null && (PluginUpdateHelper.sUpdatePluginItemMap.containsKey(installPluginItem.packageName))) {
                        installItemMap.put(installPluginItem.packageName, PluginUpdateHelper.sUpdatePluginItemMap.get(installPluginItem.packageName));
                    }
                    ++i;
                    continue;
                }
            }
            sUpdatePluginItemMap.clear();
            sUpdatePluginItemMap.putAll(installItemMap);
            ConcurrentHashMap<String, DeletePluginItem> deleteItemMap = new ConcurrentHashMap();
            if (deletePlugins != null) {
                for (int i = 0; i < deletePlugins.length(); ++i) {
                    DeletePluginItem deletePluginItem1 = DeletePluginItem.fromJO(deletePlugins.getJSONObject(i));
                    if (deletePluginItem1 != null && deletePluginItem1.b()) {
                        DeletePluginItem deletePluginItem = PluginUpdateHelper.sDeletePluginItemMap.get(deletePluginItem1.packageName);
                        if (deletePluginItem1.a(deletePluginItem)) {
                            deleteItemMap.put(deletePluginItem1.packageName, deletePluginItem1);
                        } else if (deletePluginItem != null) {
                            deleteItemMap.put(deletePluginItem1.packageName, deletePluginItem1);
                        }
                    }
                }
            }

            sDeletePluginItemMap.clear();
            sDeletePluginItemMap.putAll(deleteItemMap);
            if (Logger.debug()) {
                Logger.d("PluginUpdateHelper", "sUpdatePluginItemMap size = " + sUpdatePluginItemMap.size()
                        + " sDeletePluginItemMap size = " + sDeletePluginItemMap.size());
            }
            PluginUpdateHelper.deleteAllPlugins();
            this.save2sp();
            return true;
        } catch (Throwable throwable) {
            Logger.w("PluginUpdateHelper", "check update error: " + throwable);
            return false;
        }
    }

    public void handleMsg(Message message) {
        Object byteSoFar;
        Object[] v0_2;
        if (message != null) {
            switch (message.what) {
                case 0:
                case 1: {
                    this.handlePluginDownload();
                    return;
                }
                case 2: {
                    try {
                        if (!(message.obj instanceof Object[])) {
                            return;
                        }

                        Object[] objs = (Object[]) message.obj;
                        String packageName = (String) objs[0];
                        byteSoFar = objs[1];
                        Integer contentLength = (Integer) objs[2];
                        if (!Logger.debug()) {
                            return;
                        }
                        Logger.d("PluginUpdateHelper", "packageName = " + packageName + " byteSoFar = " + byteSoFar + " contentLength = " + contentLength);
                    } catch (Throwable throwable) {
                        throwable.printStackTrace();
                    }
                    return;
                }
                case 3: {
                    try {
                        if (!(message.obj instanceof Object[])) {
                            return;
                        }
                        v0_2 = (Object[]) message.obj;
                        String packageName = (String) v0_2[0];
                        Integer size = (Integer) v0_2[1];
                        String etag = (String) v0_2[2];
                        if (Logger.debug()) {
                            Logger.d("PluginUpdateHelper", "packageName = " + packageName + " size = " + size + " etag = " + etag);
                        }

                        InstallPluginItem installPluginItem = sUpdatePluginItemMap.get(packageName);
                        if (installPluginItem == null) {
                            return;
                        }

                        installPluginItem.contentLength = ((Integer) size);
                        installPluginItem.etag = etag;
                        this.a(installPluginItem);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return;
                }
                case 4: {
                    try {
                        if (!(message.obj instanceof Object[])) {
                            return;
                        }

                        v0_2 = (Object[]) message.obj;
                        String pkgName = (String) v0_2[0];
                        DownloadStatus downloadStatus = (DownloadStatus) v0_2[1];
                        if (Logger.debug()) {
                            Logger.d("PluginUpdateHelper", "packageName = " + pkgName + " DownloadStatus = " + downloadStatus.getTypeValue());
                        }

                        InstallPluginItem installPluginItem = sUpdatePluginItemMap.get(pkgName);
                        if (installPluginItem == null) {
                            return;
                        }

                        installPluginItem.downloadStatus = downloadStatus;
                        this.a(installPluginItem);
                        if (this.mUpdatePluginExtras == null) {
                            return;
                        }
                        if (downloadStatus != DownloadStatus.STATUS_SUCCESSFUL) {
                            return;
                        }
                        UpdatePluginExtras updatePluginExtras = this.mUpdatePluginExtras;
                        pkgName = installPluginItem.packageName;
                        if (pkgName == null) {
                            return;
                        }

                        if (pkgName.equals("com.bytedance.common.plugin.lite")) {
                            if (updatePluginExtras.mProcessType == ProcessType.MAIN
                                    && !PluginInstaller.isCommonPluginLiteInstalled()) {
                                PluginInstaller.onEvent(updatePluginExtras.mAppContext.getContext(), pkgName + ".download_success", System.currentTimeMillis() - updatePluginExtras.installStartTs, pkgName);
                                new DexInstallThread("DexInstaller").start();
                            }
                        } else if (pkgName.equals("com.bytedance.common.plugin.cronet")
                                && updatePluginExtras.mProcessType == ProcessType.MAIN
                                && !PluginInstaller.isCronetPluginInstalled()) {
                            PluginInstaller.onEvent(updatePluginExtras.mAppContext.getContext(), pkgName + ".download_success", System.currentTimeMillis() - updatePluginExtras.installStartTs, pkgName);
                            new pluginInstallThread("PluginInstaller").start();
                        }
                        com.ss.android.l.c.c();
                        return;
                    } catch (Exception e) {
                        return;
                    }
                }
            }
            return;
        }
    }

    private void loadData() {
        JSONObject v1_1;
        Iterator v2 = this.getLitePluginInfoSp().getAll().entrySet().iterator();
        while (v2.hasNext()) {
            Object v0 = v2.next();
            String v1 = (String) ((Map.Entry) v0).getKey();
            if (v1 != null && (v1.equals("plugin_check_url"))) {
                this.ssPluginConfigUrl = (String) ((Map.Entry) v0).getValue();
                continue;
            }

            if (v1 != null && (v1.startsWith("plugin_update_"))) {
                try {
                    v1_1 = new JSONObject((String) ((Map.Entry) v0).getValue());
                    if (Logger.debug()) {
                        Logger.d("PluginUpdateHelper", "loadData pluginItemJson = " + v1_1);
                    }

                    InstallPluginItem v0_2 = InstallPluginItem.fromJO(v1_1);
                    if (!v0_2.b()) {
                        continue;
                    }

                    if (this.mProcessType.getTypeValue() < v0_2.processType.getTypeValue()) {
                        continue;
                    }

                    if (Logger.debug()) {
                        Logger.d("PluginUpdateHelper", "put pluginItem = " + v0_2.packageName);
                    }

                    sUpdatePluginItemMap.put(v0_2.packageName, v0_2);
                } catch (Exception v0_1) {
                }

                continue;
            }

            if (v1 == null) {
                continue;
            }

            if (!v1.startsWith("plugin_delete_")) {
                continue;
            }

            try {
                v1_1 = new JSONObject((String) ((Map.Entry) v0).getValue());
                if (Logger.debug()) {
                    Logger.d("PluginUpdateHelper", "loadData pluginDeleteJson = " + v1_1);
                }

                DeletePluginItem v0_3 = DeletePluginItem.fromJO(v1_1);
                if (!v0_3.b()) {
                    continue;
                }

                if (this.mProcessType.getTypeValue() < ProcessType.MAIN.getTypeValue()) {
                    continue;
                }

                sDeletePluginItemMap.put(v0_3.packageName, v0_3);
            } catch (Exception v0_1) {
            }
        }
    }

    private SharedPreferences getLitePluginInfoSp() {
        String litePluginInfoSpName = com.bytedance.common.plugin.a.getPluginDepend().litePluginInfoSpName();
        int mode = Build.VERSION.SDK_INT < 11 ? Context.MODE_PRIVATE : Context.MODE_MULTI_PROCESS;
        return mContext.getSharedPreferences(litePluginInfoSpName, mode);
    }

    private void save2sp() {
        if (sUpdatePluginItemMap != null) {
            try {
                SharedPreferences.Editor editor = this.getLitePluginInfoSp().edit();
                editor.clear();
                editor.putString("plugin_check_url", this.ssPluginConfigUrl);
                Iterator<Map.Entry<String, InstallPluginItem>> iterator = sUpdatePluginItemMap.entrySet().iterator();
                while (iterator.hasNext()) {
                    InstallPluginItem installPluginItem = iterator.next().getValue();
                    if (installPluginItem != null) {
                        installPluginItem.saveData(editor, false);
                    }
                }

                Iterator<Map.Entry<String, DeletePluginItem>> iterator1 = sDeletePluginItemMap.entrySet().iterator();
                while (iterator1.hasNext()) {
                    DeletePluginItem deletePluginItem = iterator1.next().getValue();
                    if (deletePluginItem == null) {
                        continue;
                    }
                    deletePluginItem.saveData(editor, false);
                }

                SharedPreferenceCompat.commit(editor);
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        }
    }

    public static final class UpdatePluginExtras {
        private final PluginInstaller.OnPluginInstallFinishListener mOnPluginInstallFinishListener;
        private final AppContext mAppContext;
        private final ProcessType mProcessType;
        private final long installStartTs;

        public UpdatePluginExtras(PluginInstaller.OnPluginInstallFinishListener onPluginInstallFinishListener, AppContext appContext, ProcessType processType, long installStartTs) {
            this.mOnPluginInstallFinishListener = onPluginInstallFinishListener;
            this.mAppContext = appContext;
            this.mProcessType = processType;
            this.installStartTs = installStartTs;
        }
    }

    final class DownloadPluginTask extends AsyncTask {
        private volatile InstallPluginItem mRemotePluginItem;
        private PluginUpdateDownloader mPluginUpdateDownloader;

        public DownloadPluginTask(InstallPluginItem remotePluginItem) {
            this.mRemotePluginItem = remotePluginItem;
            this.mPluginUpdateDownloader = new PluginUpdateDownloader(mContext, this.mRemotePluginItem.packageName, PluginUpdateHelper.this);
        }

        private Void execDownload() {
            String outputDownloadPath;
            try {
                if (this.mRemotePluginItem == null) {
                    return null;
                }

                if (TextUtils.isEmpty(this.mRemotePluginItem.downloadUrl)) {
                    return null;
                }

                synchronized (PluginUpdateHelper.this) {
                    File downloadDir = new File(PluginUpdateHelper.downloadDir);
                    if (!downloadDir.isDirectory() && !downloadDir.mkdirs()) {
                        Logger.e("PluginUpdateHelper", "can not mkdir files dir: " + PluginUpdateHelper.downloadDir);
                        return null;
                    }
                }

                InstallPluginItem remotePluginItem = this.mRemotePluginItem;
                String downloadDir = PluginUpdateHelper.downloadDir;
                if (TextUtils.isEmpty(downloadDir)) {
                    outputDownloadPath = null;
                } else {
                    StringBuilder sb = new StringBuilder(downloadDir);
                    sb.append("/plugin_").append(remotePluginItem.apkMD5).append(".pl.part");
                    outputDownloadPath = sb.toString();
                }

                String dstFilePath = this.mRemotePluginItem.getDstFilePath(PluginUpdateHelper.downloadDir);
                this.mRemotePluginItem.apkUri = "file://" + dstFilePath;
                Logger.d("PluginUpdateHelper", "execDownload = " + this.mRemotePluginItem.packageName);
                boolean success = this.mPluginUpdateDownloader.execDownload(this.mRemotePluginItem.downloadUrl,
                        outputDownloadPath, this.mRemotePluginItem.etag,
                        this.mRemotePluginItem.contentLength.intValue());
                File dstFile = new File(dstFilePath);
                dstFile.delete();
                if (!success) {
                    return null;
                }

                File tempFile = new File(outputDownloadPath);
                if (!tempFile.isFile()) {
                    return null;
                }
                tempFile.renameTo(dstFile);
                this.mPluginUpdateDownloader.onDownloadStatusChanged(DownloadStatus.STATUS_SUCCESSFUL);
                return null;
            } catch (Exception e) {
                Logger.w("PluginUpdateHelper", "download error: " + e);
                return null;
            }
        }

        protected final Object doInBackground(Object[] params) {
            return this.execDownload();
        }
    }

    final class KillApplicationReceiver extends BroadcastReceiver {

        public final void onReceive(Context context, Intent intent) {
            if (mProcessType != ProcessType.MAIN
                    && intent != null
                    && ("com.bytedance.common.plugin.framework.update.killApplication".equals(intent.getAction()))) {
                PluginUpdateHelper.this.mWeakHandler.post(new Runnable() {
                    @Override
                    public final void run() {
                        try {
                            Process.killProcess(Process.myPid());
                        } catch (Throwable throwable) {
                            throwable.printStackTrace();
                        }
                    }
                });
            }
        }
    }

    final class ConnectivityReceiver extends BroadcastReceiver {

        public final void onReceive(Context context, Intent intent) {
            if (context != null
                    && (intent != null
                    && !TextUtils.isEmpty(intent.getAction())
                    && ("android.net.conn.CONNECTIVITY_CHANGE".equals(intent.getAction())))) {
                try {
                    if (Logger.debug()) {
                        Logger.d("PluginUpdateHelper", "ConnectivityReceiver");
                    }
                    PluginUpdateHelper.this.handlePluginDownload();
                } catch (Exception e) {
                }
            }
        }
    }
}

